當涉及到字典 (dict) 和集合 (set) 時,Python 提供了內建的資料結構來處理這些操作。以下是一個簡單的教學,其中包含了一些常見的字典和集合操作,並附上相關的範例程式碼。

  1. 字典建立
    在 Python 中,你可以使用花括號 {} 來建立字典。字典由鍵 (key) 和值 (value) 的鍵值對組成。

     dict1 = {'apple': 3, 'banana': 5, 'orange': 2}
     dict2 = {1: 'one', 2: 'two', 3: 'three'}
    
  2. 字典的存取
    你可以使用鍵 (key) 來存取字典中的值。

     print(dict1['apple'])    # 輸出: 3
     print(dict2[2])         # 輸出: 'two'
    
  3. 字典的修改
    字典是可變的資料結構,你可以通過鍵 (key) 進行修改、新增或刪除鍵值對。

     dict1['apple'] = 4
     print(dict1)     # 輸出: {'apple': 4, 'banana': 5, 'orange': 2}
    
     dict1['grape'] = 7
     print(dict1)     # 輸出: {'apple': 4, 'banana': 5, 'orange': 2, 'grape': 7}
    
     del dict1['orange']
     print(dict1)     # 輸出: {'apple': 4, 'banana': 5, 'grape': 7}
    
  4. 字典的迭代
    你可以使用迴圈遍歷字典中的鍵值對。

     for key in dict1:
         print(key, dict1[key])
    
  5. 字典的長度
    你可以使用 len() 函式來獲取字典中鍵值對的數量。

     print(len(dict1))    # 輸出: 3
    
  6. 集合建立
    在 Python 中,你可以使用花括號 {}set() 函式來建立集合。

     set1 = {1, 2, 3, 4, 5}
     set2 = set([3, 4, 5, 6, 7])
    
  7. 集合的存取
    由於集合是無序的,你無法使用索引 (index) 存取集合中的元素。你只能檢查元素是否存在於集合中。

     print(3 in set1)     # 輸出: True
     print(6 in set2)     # 輸出: True
    
  8. 集合的修改
    集合是可變的資料結構,你可以透過添加或刪除元素來修改集合。

     set1.add(6)
     print(set1)     # 輸出: {1, 2, 3, 4, 5, 6}
    
     set2.remove(7)
     print(set2)     # 輸出: {3, 4, 5, 6}
    
  9. 集合的數學運算
    你可以使用集合進行聯集、交集、差集等數學運算。

     set3 = {4, 5, 6, 7, 8}
     union_set = set1.union(set3)
     print(union_set)    # 輸出: {1, 2, 3, 4, 5, 6, 7, 8}
    
     intersection_set = set1.intersection(set3)
     print(intersection_set)    # 輸出: {4, 5, 6}
    
     difference_set = set1.difference(set3)
     print(difference_set)    # 輸出: {1, 2, 3}
    

以上是一些 Python 中處理字典和集合的基本操作。Python 還提供了許多其他有用的方法和函式,可用於進一步處理字典和集合。希望這個教學能幫助你入門字典和集合的基礎操作!

#Python







你可能感興趣的文章

JavaScript - Sort( ) 到底怎麼用?

JavaScript - Sort( ) 到底怎麼用?

PM 工作流程解析與怎麼寫 PRD

PM 工作流程解析與怎麼寫 PRD

有空的話來學一下 Tailwind CSS - Week 2

有空的話來學一下 Tailwind CSS - Week 2






留言討論